<?php
/**
 * Created by PhpStorm.
 * User: liuxin
 * Date: 2018/1/29
 * Time: 下午4:26
 */
namespace common\components;

use Codeception\Module\Yii2;

class Rsa
{
    public static function encrypt($content, $key = null)
    {
        if ($key === null) {
            $key = self::getKey('public');
        }

        openssl_public_encrypt($content, $encrypted, $key);

        return base64_encode($encrypted);
    }

    public static function decrypt($content, $key = null)
    {
        if ($key === null) {
            $key = self::getKey('private');
        }

        $encrypted = base64_decode($content);

        openssl_private_decrypt($encrypted, $decrypted, $key);

        return $decrypted;
    }

    public static function getKey($type)
    {
        $file = \Yii::getAlias("@common")."/config/rsa/".$type . "_key.pem";
        if (! file_exists($file)) {
            return false;
        }

        if($type == 'private')
        {
            return openssl_pkey_get_private(file_get_contents($file), 1234);
        } else {
            return openssl_pkey_get_public(file_get_contents($file));
        }
    }
}
